/*
 * @Description: 聊天内容hook
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2025-04-29
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-04-29
 */

import { computed, ref } from 'vue'

import type { IMChatMessage } from '/@/components/im'
import { useIM } from '/@/components/im'

const { getChatMessages } = useIM()

export const useMessage = (userId: string) => {
  /** 聊天内容 */
  const messages = ref([] as IMChatMessage[])

  /** 选中的聊天内容 */
  const checkedMessage = computed(() => {
    if (!checkedMemberId.value) return null
    return messages.value.find((item) => item.memberId === checkedMemberId.value)
  })

  /**
   * 初始化聊天内容
   * @param userId 用户id
   * @returns
   */
  const initMessage = async () => {
    if (!checkedMemberId.value) return
    if (checkedMessage.value) return
    const res = await getChatMessages({ senderId: checkedMemberId.value, recipientId: userId })
    messages.value.push({ memberId: checkedMemberId.value, messageItems: res ?? [] })
  }

  /**
   * 添加聊天内容
   * @param message 消息内容
   */
  const addMessage = async (message: ChatImMessagePageTypes.IResponse) => {
    const findedMessage = messages.value.find((item) => [message.senderId, message.recipientId].includes(item.memberId))
    findedMessage?.messageItems.unshift(message)
  }

  /** 选中的成员id */
  const checkedMemberId = ref('')

  /**
   * 设置选中的成员id
   * @param memberId 成员id
   * @returns
   */
  const setMessageCheckedMemberId = (memberId: string) => (checkedMemberId.value = memberId)

  return {
    messages,
    checkedMessage,
    initMessage,
    addMessage,
    setMessageCheckedMemberId,
  }
}

export default useMessage
